package com.ebspp.server.replication;

import java.util.List;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

import com.ebspp.global.General;
import com.ebspp.thrift.DataMsg;
import com.ebspp.thrift.Identity;
import com.ebspp.thrift.ResourceType;
import com.ebspp.thrift.Watcher;

public class WatchConnection {

	private String watcher;
	private Identity wID;
	private ResourceType resType;
	
	private Watcher.Client waClient;
	private TTransport transport;
	
	Object mutex = new Object();
	
	public WatchConnection(String watcher, ResourceType resType, Identity wID)
	{
		this.watcher = watcher;
		this.resType = resType;
		this.wID = wID;
	}
	
	public void connect() throws TTransportException
	{
		transport = new TSocket(watcher, General.waPort);
		//TTransport wTransport = new TFramedTransport(socket);
		TProtocol protocol = new TBinaryProtocol(transport);
		waClient = new Watcher.Client(protocol);
		transport.open();
	}
	
	public void close()
	{
		transport.close();
	}
	
	public void notify(List<DataMsg> data) throws TException
	{
		synchronized(mutex)
		{
			waClient.notify(data, resType, wID);
		}
	}
	
	public String getWatcher()
	{
		return watcher;
	}
	
	
	public boolean equals(Object obj)
	{
		if(obj == null)
			return false;
		if(obj instanceof WatchConnection)
		{
			WatchConnection conn = (WatchConnection)obj;
			if(wID.equals(conn.wID) && watcher.equals(conn.watcher) && resType.equals(conn.resType))
				return true;
		}
		return false;
	}
	
	public int hashCode()
	{
		return wID.hashCode() * 3 + watcher.hashCode() * 13 + resType.hashCode() * 17;
	}

}
